home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 5 / BBS in a Box -Volume V (BBS in a Box) (April 1992).iso / Files / Prog / M / Mac gperf 1.9.cpt / Mac gperf 1.9 / src / keylist.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-03-11  |  34.3 KB  |  1,111 lines  |  [TEXT/KAHL]

  1. /* Routines for building, ordering, and printing the keyword list.
  2.    Copyright (C) 1989 Free Software Foundation, Inc.
  3.    written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  4.  
  5. This file is part of GNU GPERF.
  6.  
  7. GNU GPERF is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 1, or (at your option)
  10. any later version.
  11.  
  12. GNU GPERF is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16.  
  17. You should have received a copy of the GNU General Public License
  18. along with GNU GPERF; see the file COPYING.  If not, write to
  19. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. #include <stdio.h>
  22. #include <assert.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25.  
  26. #include "options.h"
  27. #include "readline.h"
  28. #include "hashtable.h"
  29. #include "stderr.h"
  30. #include "xmalloc.h"
  31. #include "gperf.h"
  32. #include "perfect.h"
  33.  
  34. #include "keylist.h"
  35.  
  36.     /* Used in function reorder, below. */
  37.  
  38. static bool determined[ALPHABET_SIZE]; 
  39.  
  40.     /* Default type for generated code. */
  41.  
  42. static char *    default_array_type = "char *";
  43.  
  44.     /* Generated function ``in_word_set'' default return type. */
  45.     
  46. static char *    default_return_type = "char *";
  47.  
  48.     /* Largest positive integer value. */
  49.     /* Most negative integer value. */
  50.  
  51. #if 0
  52.     /* these are the original definitions, which don't work
  53.         under Think C (MAX_INT = -1, NEG_MAX_INT = 0). Think C has
  54.         16-bit ints, so the following values are correct */
  55.  
  56.     #define MAX_INT            ((~(unsigned)0)>>1)
  57.     #define NEG_MAX_INT        ((~(unsigned)0)^((~(unsigned)0)>>1))
  58. #else
  59.     #define MAX_INT            32767
  60.     #define NEG_MAX_INT        -32767
  61. #endif
  62.  
  63.     /* How wide the printed field width must be to contain the maximum hash value. */
  64.  
  65. static int        field_width = 2;
  66.  
  67.     /* Globally visible KEY_LIST object. */
  68.  
  69. KEY_LIST        key_list;
  70.  
  71. /*******************************************************************************\
  72. *                              Prototypes                                        *
  73. \*******************************************************************************/
  74.  
  75. static char *        get_special_input( char delimiter );
  76. static char *        save_include_src( void );
  77. static char *        get_array_type( void );
  78. static void            set_output_types( void );
  79. static LIST_NODE *    merge( LIST_NODE * list1, LIST_NODE * list2 );
  80. static LIST_NODE *    merge_sort( LIST_NODE * head );
  81. static int            get_occurrence( LIST_NODE * ptr );
  82. static void            set_determined( LIST_NODE * ptr );
  83. static bool            already_determined( LIST_NODE * ptr );
  84. static int            print_min_max( void );
  85. static void            print_switch( void );
  86. static void            print_keylength_table( void );
  87. static void            print_keyword_table( void );
  88. static void            print_hash_function( int max_hash_value );
  89. static void            print_lookup_function( void );
  90. static void            dump( void );
  91.  
  92.  
  93.     /***********************************************************************\
  94.     *                                                                        *
  95.     * name:        get_special_input                                            *
  96.     *                                                                        *
  97.     * descr:    Gathers the input stream into a buffer.                        *
  98.     *                                                                        *
  99.     \***********************************************************************/
  100.  
  101. /* Gathers the input stream into a buffer until one of two things occur:
  102.  
  103.    1. We read a '%' followed by a '%'
  104.    2. We read a '%' followed by a '}'
  105.  
  106.    The first symbolizes the beginning of the keyword list proper,
  107.    The second symbolizes the end of the C source code to be generated
  108.    verbatim in the output file.
  109.  
  110.    I assume that the keys are separated from the optional preceding struct
  111.    declaration by a consecutive % followed by either % or } starting in 
  112.    the first column. The code below uses an expandible buffer to scan off 
  113.    and return a pointer to all the code (if any) appearing before the delimiter. */
  114.  
  115. static char * get_special_input( char delimiter )
  116.     int            size  = 80;
  117.     char *        buf = xmalloc( size );
  118.     int            c;
  119.     int            i;
  120.  
  121.     for ( i = 0; ( c = getc( KeyFile ) ) != EOF; i++ )
  122.     {
  123.         if ( c == '%' )
  124.         {
  125.             if ( ( c = getc( KeyFile ) ) == delimiter )
  126.             {
  127.                 while ( ( c = getc( KeyFile ) ) != '\n' )
  128.                     ; /* Discard newline. */
  129.  
  130.                 if ( i == 0 )
  131.                     return "";
  132.                 else
  133.                 {
  134.                     buf[ delimiter == '%' && buf[i - 2] == ';' ? i - 2 : i - 1 ] = '\0';
  135.                     return buf;
  136.                 }
  137.             }
  138.             else
  139.                 ungetc( c, KeyFile );
  140.         }
  141.         else if ( i >= size )        /* Yikes, time to grow the buffer! */
  142.         { 
  143.             char *    temp = xmalloc( size *= 2 );
  144.             int        j;
  145.  
  146.             for ( j = 0; j < i; j++ )
  147.                 temp[ j ] = buf[ j ];
  148.  
  149.             free( buf );
  150.             buf = temp;
  151.         }
  152.         buf[  i] = c;
  153.     }
  154.  
  155.     return NULL;        /* Problem here. */
  156. }
  157.  
  158.     /***********************************************************************\
  159.     *                                                                        *
  160.     * name:        save_include_src                                            *
  161.     *                                                                        *
  162.     * descr:    Stores any C text that must be included verbatim into         *
  163.     *            the generated code output.                                    *
  164.     *                                                                        *
  165.     \***********************************************************************/
  166.  
  167. static char * save_include_src()
  168. {
  169.     int        c;
  170.   
  171.     if ( ( c = getc( KeyFile ) ) != '%' )
  172.     {
  173.         ungetc( c, KeyFile );
  174.         return "";
  175.     }
  176.     else if ( ( c = getc( KeyFile ) ) != '{' )
  177.         report_error( "internal error, %c != '{' on line %d in file %s%a",
  178.                         c, __LINE__, __FILE__);
  179.  
  180.         /* NOT REACHED */
  181.  
  182.     else 
  183.         return get_special_input( '}' );
  184. }
  185.  
  186.  
  187.     /***********************************************************************\
  188.     *                                                                        *
  189.     * name:        strcspn                                                        *
  190.     *                                                                        *
  191.     * descr:    description                                                    *
  192.     *                                                                        *
  193.     \***********************************************************************/
  194.  
  195. #if 0
  196.     /* the following is in the ANSI library */
  197.     
  198. /* strcspn - find length of initial segment of s consisting entirely
  199.    of characters not from reject (borrowed from Henry Spencer's
  200.    ANSI string package). */
  201.  
  202. static int
  203. strcspn (s, reject)
  204.      char *s;
  205.      char *reject;
  206. {
  207.   char *scan;
  208.   char *rej_scan;
  209.   int   count = 0;
  210.  
  211.   for (scan = s; *scan; scan++) 
  212.     {
  213.  
  214.       for (rej_scan = reject; *rej_scan;) 
  215.         if (*scan == *rej_scan++)
  216.           return count;
  217.  
  218.       count++;
  219.     }
  220.  
  221.   return count;
  222. }
  223. #endif
  224.  
  225.  
  226.     /***********************************************************************\
  227.     *                                                                        *
  228.     * name:        get_array_type                                                *
  229.     *                                                                        *
  230.     * descr:    Determines from the input file whether the user wants to    *
  231.     *            build a table from a user-defined struct, or whether the    *
  232.     *            user is content to simply use the default array of keys.    *
  233.     *                                                                        *
  234.     \***********************************************************************/
  235.  
  236. static char * get_array_type()
  237. {
  238.     return get_special_input ('%');
  239. }
  240.  
  241.     /***********************************************************************\
  242.     *                                                                        *
  243.     * name:        set_output_types                                            *
  244.     *                                                                        *
  245.     * descr:    Sets up the Return_Type, the Struct_Tag type and the         *
  246.     *            Array_Type based on various user options.                    *
  247.     *                                                                        *
  248.     \***********************************************************************/
  249.  
  250. static void set_output_types()
  251. {
  252.   
  253.   if (OPTION_ENABLED (option, TYPE) && !(key_list.array_type = get_array_type ()))
  254.     return;                     /* Something's wrong, bug we'll catch it later on.... */
  255.   else if (OPTION_ENABLED (option, TYPE))        /* Yow, we've got a user-defined type... */
  256.     {    
  257.       int struct_tag_length = strcspn (key_list.array_type, "{\n\0");
  258.       
  259.       if (OPTION_ENABLED (option, POINTER))      /* And it must return a pointer... */
  260.         {    
  261.           key_list.return_type = xmalloc (struct_tag_length + 2);
  262.           strncpy (key_list.return_type, key_list.array_type, struct_tag_length);
  263.           key_list.return_type[struct_tag_length] = '\0';
  264.           strcat (key_list.return_type, "*");
  265.         }
  266.       
  267.       key_list.struct_tag = (char *) xmalloc (struct_tag_length + 1);
  268.       strncpy (key_list.struct_tag, key_list.array_type, struct_tag_length);
  269.       key_list.struct_tag[struct_tag_length] = '\0';
  270.     }  
  271.   else if (OPTION_ENABLED (option, POINTER))     /* Return a char *. */
  272.     key_list.return_type = default_array_type;
  273. }
  274.  
  275.     /***********************************************************************\
  276.     *                                                                        *
  277.     * name:        read_keys                                                    *
  278.     *                                                                        *
  279.     * descr:    Read in all the keys from the input file and create a         *
  280.     *            linked list pointed to by Head. This list is then             *
  281.     *            quickly checked for "links", ie unhashable elements         *
  282.     *            possessing identical key sets and lengths.                    *
  283.     *                                                                        *
  284.     \***********************************************************************/
  285.  
  286. void read_keys()
  287. {
  288.     char *            ptr;
  289.     LIST_NODE *        temp;
  290.     LIST_NODE *        trail;
  291.   
  292.     key_list.include_src = save_include_src();
  293.     set_output_types();
  294.  
  295.         /*
  296.         **    Make sure that the input file is ok
  297.         */
  298.         
  299.     if ( ! ( ptr = read_line() ) ) 
  300.         report_error ("No words in input file, did you forget to prepend %s or use -t accidentally?\n%a", "%%");
  301.  
  302.         /*
  303.         **    Read in all the keywords from the input file.
  304.         */
  305.  
  306.     key_list.head = make_list_node( ptr, strcspn( ptr, ",\n" ) );
  307.     for ( temp = key_list.head; ( ptr = read_line() ) && strcmp( ptr, "%%" ); temp = temp->next )
  308.     {
  309.         temp->next = make_list_node( ptr, strcspn( ptr, ",\n") );
  310.         key_list.total_keys++;
  311.     }
  312.       
  313.         /* See if any additional C code is included at end of this file. */
  314.  
  315.     if ( ptr )
  316.         key_list.additional_code = TRUE;
  317.  
  318.  
  319.     {
  320.         bool    link = FALSE;            /* If this becomes TRUE we've got a link. */
  321.         int        table_multiple = 5;        /* hash table size multiplier times # keywords */
  322.  
  323.             /* Make large hash table for efficiency. */
  324.  
  325.         hash_table_init( (key_list.list_len = key_list.total_keys) * table_multiple ); 
  326.  
  327.             /*    Test whether there are any links and also set the maximum length of
  328.                 an identifier in the keyword list.        */
  329.       
  330.         for ( temp = key_list.head, trail = NULL; temp; temp = temp->next )
  331.         {
  332.             LIST_NODE *        ptr = retrieve( temp, OPTION_ENABLED( option, NOLENGTH ) );
  333.           
  334.                 /*    Check for links.  We deal with these by building an equivalence class
  335.                     of all duplicate values (i.e., links) so that only 1 keyword is
  336.                     representative of the entire collection.  This *greatly* simplifies
  337.                     processing during later stages of the program.        */
  338.  
  339.             if ( ptr )              
  340.             {                   
  341.                 key_list.list_len--;
  342.                 trail->next = temp->next;
  343.                 temp->link  = ptr->link;
  344.                 ptr->link   = temp;
  345.                 link        = TRUE;
  346.  
  347.                     /* Complain if user hasn't enabled the duplicate option. */
  348.             
  349.                 if ( !OPTION_ENABLED( option, DUP ) )
  350.                     report_error( "Key link: \"%s\" = \"%s\", with key set \"%s\".\n",
  351.                                     temp->key, ptr->key, temp->key_set );
  352.                 else if ( OPTION_ENABLED( option, DEBUG ) )
  353.                     report_error( "Key link: \"%s\" = \"%s\", with key set \"%s\".\n",
  354.                                       temp->key, ptr->key, temp->key_set );                
  355.             }
  356.             else
  357.                 trail = temp;
  358.             
  359.                 /*    Update minimum and maximum keyword length, if needed. */
  360.         
  361.             if ( temp->length > key_list.max_key_len ) 
  362.                 key_list.max_key_len = temp->length;
  363.             if ( temp->length < key_list.min_key_len ) 
  364.                 key_list.min_key_len = temp->length;
  365.         }
  366.  
  367.             /*    Exit program if links exists and option[DUP] not set,
  368.                 since we can't continue */
  369.  
  370.         if ( link ) 
  371.         {
  372.             if ( OPTION_ENABLED( option, DUP ) )
  373.             {
  374.                 if ( !OPTION_ENABLED( option, SWITCH ) )
  375.                 {
  376.                     report_error( "turning on -S option.\n" );
  377.                     SET_OPTION( option, SWITCH );
  378.                 }
  379.                 report_error( "Some input keys have identical hash values, examine"
  380.                               "output carefully...\n" );
  381.             }
  382.             else
  383.                 report_error( "Some input keys have identical hash values,\n"
  384.                               "try different key positions or use option -D.\n%a" );
  385.         }
  386.         else if ( OPTION_ENABLED( option, DUP ) )
  387.         {
  388.                 /*    If no links, clear the DUP option so we can use the length
  389.                           table, if output.        */
  390.  
  391.             UNSET_OPTION( option, DUP );
  392.         }
  393.     }
  394. }
  395.  
  396.  
  397.     /***********************************************************************\
  398.     *                                                                        *
  399.     * name:        merge                                                        *
  400.     *                                                                        *
  401.     * descr:    Recursively merges two sorted lists together to form one    *
  402.     *            sorted list. The ordering criteria is by frequency of         *
  403.     *            occurrence of elements in the key set or by hash value.     *
  404.     *                                                                        *
  405.     * note:        This is a kludge, but permits nice sharing of almost         *
  406.     *            identical code without incurring the overhead of a             *
  407.     *            function call comparison.                                    *
  408.     *                                                                        *
  409.     \***********************************************************************/
  410.   
  411. static LIST_NODE * merge( LIST_NODE * list1, LIST_NODE * list2 )
  412. {
  413.   if (!list1)
  414.     return list2;
  415.   else if (!list2)
  416.     return list1;
  417.   else if (key_list.occurrence_sort && list1->occurrence < list2->occurrence
  418.            || key_list.hash_sort && list1->hash_value > list2->hash_value)
  419.     {
  420.       list2->next = merge (list2->next, list1);
  421.       return list2;
  422.     }
  423.   else
  424.     {
  425.       list1->next = merge (list1->next, list2);
  426.       return list1;
  427.     }
  428. }
  429.  
  430. /* Applies the merge sort algorithm to recursively sort the key list by
  431.    frequency of occurrence of elements in the key set. */
  432.   
  433. static LIST_NODE * merge_sort( LIST_NODE * head )
  434.   if (!head || !head->next)
  435.     return head;
  436.   else
  437.     {
  438.       LIST_NODE *middle = head;
  439.       LIST_NODE *temp   = head->next->next;
  440.     
  441.       while (temp)
  442.         {
  443.           temp   = temp->next;
  444.           middle = middle->next;
  445.           if (temp)
  446.             temp = temp->next;
  447.         } 
  448.     
  449.       temp         = middle->next;
  450.       middle->next = NULL;
  451.       return merge (merge_sort (head), merge_sort (temp));
  452.     }   
  453. }
  454.  
  455. /* Returns the frequency of occurrence of elements in the key set. */
  456.  
  457. static int get_occurrence( LIST_NODE * ptr )
  458. {
  459.   int   value = 0;
  460.   char *temp;
  461.  
  462.   for (temp = ptr->key_set; *temp; temp++)
  463.     value += occurrences[*temp];
  464.   
  465.   return value;
  466. }
  467.  
  468. /* Enables the index location of all key set elements that are now 
  469.    determined. */
  470.   
  471. static void set_determined( LIST_NODE * ptr )
  472. {
  473.   char *temp;
  474.   
  475.   for (temp = ptr->key_set; *temp; temp++)
  476.     determined[*temp] = TRUE;
  477.   
  478. }
  479.  
  480. /* Returns TRUE if PTR's key set is already completely determined. */
  481.  
  482. static bool already_determined( LIST_NODE * ptr )
  483. {
  484.   bool  is_determined = TRUE;
  485.   char *temp;
  486.  
  487.   for (temp = ptr->key_set; is_determined && *temp; temp++)
  488.     is_determined = determined[*temp];
  489.   
  490.   return is_determined;
  491. }
  492.  
  493. /* Reorders the table by first sorting the list so that frequently occuring 
  494.    keys appear first, and then the list is reorded so that keys whose values 
  495.    are already determined will be placed towards the front of the list.  This
  496.    helps prune the search time by handling inevitable collisions early in the
  497.    search process.  See Cichelli's paper from Jan 1980 JACM for details.... */
  498.  
  499. void reorder()
  500. {
  501.   LIST_NODE *ptr;
  502.  
  503.   for (ptr = key_list.head; ptr; ptr = ptr->next)
  504.     ptr->occurrence = get_occurrence (ptr);
  505.   
  506.   key_list.hash_sort       = FALSE;
  507.   key_list.occurrence_sort = TRUE;
  508.   
  509.   for (ptr = key_list.head = merge_sort (key_list.head); ptr->next; ptr = ptr->next)
  510.     {
  511.       set_determined (ptr);
  512.     
  513.       if (already_determined (ptr->next))
  514.         continue;
  515.       else
  516.         {
  517.           LIST_NODE *trail_ptr = ptr->next;
  518.           LIST_NODE *run_ptr   = trail_ptr->next;
  519.       
  520.           for (; run_ptr; run_ptr = trail_ptr->next)
  521.             {
  522.         
  523.               if (already_determined (run_ptr))
  524.                 {
  525.                   trail_ptr->next = run_ptr->next;
  526.                   run_ptr->next   = ptr->next;
  527.                   ptr = ptr->next = run_ptr;
  528.                 }
  529.               else
  530.                 trail_ptr = run_ptr;
  531.             }
  532.         }
  533.     }     
  534. }
  535.  
  536. /* Determines the maximum and minimum hash values.  One notable feature is 
  537.    Ira Pohl's optimal algorithm to calculate both the maximum and minimum
  538.    items in a list in O(3n/2) time (faster than the O (2n) method). 
  539.    Returns the maximum hash value encountered. */
  540.   
  541. static int print_min_max()
  542. {
  543.     int            min_hash_value;
  544.     int            max_hash_value;
  545.     LIST_NODE *    temp;
  546.  
  547.         /*
  548.         **    If the list is odd, preprocess first item
  549.         **    (rest of list then becomes even). Otherwise
  550.         **    just set up for search.
  551.         */
  552.  
  553.     if ( ODD( key_list.list_len ) )
  554.     {
  555.         min_hash_value    = max_hash_value = key_list.head->hash_value;
  556.         temp            = key_list.head->next;
  557.     }
  558.     else
  559.     {
  560.         min_hash_value = MAX_INT;
  561.         max_hash_value = NEG_MAX_INT;
  562.         temp           = key_list.head;
  563.     }
  564.  
  565.         /**
  566.         ***  Find max and min (search is optimal,
  567.         ***  takes O(3n/2) time).
  568.         **/
  569.  
  570.     for ( ; temp; temp = temp->next )
  571.     { 
  572.         static int        i;
  573.         int                key_2;
  574.         int                key_1 = temp->hash_value;
  575.  
  576.         temp  = temp->next;
  577.         key_2 = temp->hash_value;
  578.         i++;
  579.  
  580.         if ( key_1 < key_2 )
  581.         {
  582.             if ( key_1 < min_hash_value )
  583.                 min_hash_value = key_1;
  584.             if ( key_2 > max_hash_value )
  585.                 max_hash_value = key_2;
  586.         }
  587.         else
  588.         {
  589.             if ( key_2 < min_hash_value )
  590.                 min_hash_value = key_2;
  591.             if ( key_1 > max_hash_value )
  592.                 max_hash_value = key_1;
  593.         }
  594.     }
  595.  
  596.     printf( "\n"
  597.             "#define MIN_WORD_LENGTH %d\n"
  598.             "#define MAX_WORD_LENGTH %d\n"
  599.             "#define MIN_HASH_VALUE %d\n"
  600.             "#define MAX_HASH_VALUE %d\n"
  601.             "/*\n"
  602.             "%5d keywords\n"
  603.             "%5d is the maximum key range\n"
  604.             "*/\n"
  605.             "\n",
  606.             (int)( ( key_list.min_key_len == MAX_INT ) ? key_list.max_key_len : key_list.min_key_len ),
  607.             (int)key_list.max_key_len,
  608.             (int)min_hash_value,
  609.             (int)max_hash_value,
  610.             (int)key_list.total_keys,
  611.             (int)( max_hash_value - min_hash_value + 1 )
  612.           );
  613.  
  614.     return max_hash_value;
  615. }
  616.  
  617.  
  618.     /***********************************************************************\
  619.     *                                                                        *
  620.     * name:        print_switch                                                *
  621.     *                                                                        *
  622.     * descr:    Generates the output using a C switch. This trades             *
  623.     *            increased search time for decreased table space             *
  624.     *            (potentially *much* less space for sparse tables).            *
  625.     *                                                                        *
  626.     \***********************************************************************/
  627.  
  628. /*    If the user has specified their own struct in the keyword file *and*
  629.     they enable the POINTER option we have extra work to do.  The solution
  630.     here is to maintain a local static array of user defined struct's, as
  631.     with the Print_Lookup_Function.  Then we use for switch statements to
  632.     perform a strcmp or strncmp, returning 0 if the str fails to match, and
  633.     otherwise returning a pointer to appropriate index location in the local
  634.     static array. */
  635.  
  636. static void print_switch()
  637. {
  638.     char *        comp_buffer = 0;
  639.     int            pointer_and_type_enabled = OPTION_ENABLED( option, POINTER ) && OPTION_ENABLED( option, TYPE );
  640.     size_t        allocSize;
  641.     
  642.     if ( pointer_and_type_enabled )
  643.     {
  644.         allocSize = strlen ("*str == *resword->%s && !strncmp (str + 1, resword->%s + 1, len - 1)"
  645.                                              + 2 * strlen (GET_KEY_NAME (option)) + 1);
  646.                                              
  647.         comp_buffer = (char *) malloc( allocSize );
  648.  
  649.         sprintf( comp_buffer, OPTION_ENABLED (option, COMP)
  650.                 ? "*str == *resword->%s && !strncmp (str + 1, resword->%s + 1, len - 1)"
  651.                 : "*str == *resword->%s && !strcmp (str + 1, resword->%s + 1)", GET_KEY_NAME (option), GET_KEY_NAME (option));
  652.     }
  653.     else
  654.         comp_buffer = OPTION_ENABLED (option, COMP) 
  655.                     ? "*str == *resword && !strncmp (str + 1, resword + 1, len - 1)" 
  656.                     : "*str == *resword && !strcmp (str + 1, resword + 1)";
  657.  
  658.     printf( "  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n    {\n\
  659.       register int key = %s (str, len);\n\n\
  660.       if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n        {\n",
  661.           GET_HASH_NAME (option));
  662.  
  663.     /* Output each keyword as part of a switch statement indexed by hash value. */
  664.  
  665.     if (OPTION_ENABLED (option, POINTER) || OPTION_ENABLED (option, DUP))
  666.     {
  667.       LIST_NODE *temp;
  668.  
  669.       printf ("          %s%s *resword; %s\n\n          switch (key)\n            {\n",
  670.               OPTION_ENABLED (option, CONST) ? "const " : "",
  671.               pointer_and_type_enabled ? key_list.struct_tag : "char", 
  672.               OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP) ? "int key_len;" : "");
  673.  
  674.       for (temp = key_list.head; temp; temp = temp->next)
  675.         {
  676.           printf ("            case %*d:\n", field_width, temp->hash_value);
  677.  
  678.           if (temp->link)
  679.             {
  680.               LIST_NODE *links;
  681.  
  682.               for (links = temp; links; links = links->link)
  683.                 {
  684.                   if (pointer_and_type_enabled)
  685.                     printf ("              resword = &wordlist[%d];\n", links->index);
  686.                   else
  687.                     printf ("              resword = \"%s\";\n", links->key); 
  688.                   printf ("              if (%s) return resword;\n", comp_buffer);
  689.                 }
  690.               printf ("              return 0;\n");
  691.             }
  692.           else if (temp->next && temp->hash_value == temp->next->hash_value)
  693.             {
  694.  
  695.               for ( ; temp->next && temp->hash_value == temp->next->hash_value;
  696.                    temp = temp->next)
  697.                 {
  698.                   if (pointer_and_type_enabled)
  699.                     printf ("              resword = &wordlist[%d];\n", temp->index);
  700.                   else
  701.                     printf ("              resword = \"%s\";\n", temp->key);
  702.                   printf ("              if (%s) return resword;\n", comp_buffer);
  703.                 }
  704.               if (pointer_and_type_enabled)
  705.                 printf ("              resword = &wordlist[%d];\n", temp->index);
  706.               else
  707.                 printf ("              resword = \"%s\";\n", temp->key);
  708.               printf ("              return %s ? resword : 0;\n", comp_buffer);
  709.             }
  710.           else 
  711.             {
  712.               if (pointer_and_type_enabled)
  713.                 printf ("              resword = &wordlist[%d];", temp->index);
  714.               else 
  715.                 printf ("              resword = \"%s\";", temp->key);
  716.               if (OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP))
  717.                 printf (" key_len = %d;", temp->length);
  718.               printf (" break;\n");
  719.             }
  720.         }
  721.       printf ("            default: return 0;\n            }\n");
  722.       printf (OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP)
  723.               ? "          if (len == key_len && %s)\n            return resword;\n"
  724.               : "          if (%s)\n            return resword;\n", comp_buffer);
  725.       printf ("      }\n  }\n  return 0;\n}\n");
  726.     }
  727.     else                          /* Nothing special required here. */
  728.     {                        
  729.         LIST_NODE *temp;
  730.  
  731.         printf ("          char *s = \"\";\n\n          switch (key)\n            {\n");
  732.       
  733.         for ( temp = key_list.head; temp; temp = temp->next )
  734.             if (OPTION_ENABLED (option, LENTABLE))
  735.                 printf ("            case %*d: if (len == %d) s = \"%s\"; else return 0; break;\n", 
  736.                   field_width, temp->hash_value, temp->length, temp->key);
  737.             else
  738.                 printf ("            case %*d: s = \"%s\"; break;\n",
  739.                   field_width, temp->hash_value, temp->key);
  740.  
  741.         printf( "            default: return 0;\n            }\n          return *s == *str && !%s;\n        }\n    }\n  return 0;\n}\n", 
  742.               OPTION_ENABLED (option, COMP) ? "strncmp (s + 1, str + 1, len - 1)" : "strcmp (s + 1, str + 1)");
  743.     }
  744.  
  745.     if ( comp_buffer )
  746.         free( comp_buffer );
  747. }
  748.  
  749.     /***********************************************************************\
  750.     *                                                                        *
  751.     * name:        print_keylength_table                                        *
  752.     *                                                                        *
  753.     * descr:    Prints out a table of keyword lengths, for use with the     *
  754.     *            comparsion code in generated function "in_word_set"            *
  755.     *                                                                        *
  756.     \***********************************************************************/
  757.  
  758. static void print_keylength_table()
  759. {
  760.   int        max_column = 15;
  761.   int        index      = 0;
  762.   int        column     = 0;
  763.   char      *indent     = OPTION_ENABLED (option, GLOBAL) ? "" : "  ";
  764.   LIST_NODE *temp;
  765.  
  766.   if (!OPTION_ENABLED (option, DUP) && !OPTION_ENABLED (option, SWITCH)) 
  767.     {
  768.       printf ("\n%sstatic %sunsigned %s lengthtable[] =\n%s%s{\n    ",
  769.               indent, OPTION_ENABLED (option, CONST) ? "const " : "",
  770.               key_list.max_key_len < 256 ? "char" :
  771.               (key_list.max_key_len < 65536 ? "short" : "long"),
  772.               indent, indent);
  773.   
  774.       for (temp = key_list.head; temp; temp = temp->next, index++)
  775.         {
  776.     
  777.           if (index < temp->hash_value)
  778.             {
  779.       
  780.               for ( ; index < temp->hash_value; index++)
  781.                 printf ("%3d%s", 0, ++column % (max_column - 1) ? "," : ",\n    ");
  782.             }
  783.     
  784.           printf ("%3d%s", temp->length, ++column % (max_column - 1 ) ? "," : ",\n    ");
  785.         }
  786.   
  787.       printf ("\n%s%s};\n\n", indent, indent);
  788.     }
  789. }
  790.  
  791. /* Prints out the array containing the key words for the Perfect
  792.    hash function. */
  793.   
  794. static void print_keyword_table()
  795. {
  796.   char      *l_brace      = *key_list.head->rest ? "{" : "";
  797.   char      *r_brace      = *key_list.head->rest ? "}," : "";
  798.   int        doing_switch = OPTION_ENABLED (option, SWITCH);
  799.   char      *indent       = OPTION_ENABLED (option, GLOBAL) ? "" : "  ";
  800.   int        index        = 0;
  801.   LIST_NODE *temp;
  802.  
  803.   printf ("\n%sstatic %s%s wordlist[] =\n%s%s{\n", 
  804.           indent, OPTION_ENABLED (option, CONST) ? "const " : "",
  805.           key_list.struct_tag, indent, indent);
  806.   
  807.   /* Generate an array of reserved words at appropriate locations. */
  808.   
  809.     for (temp = key_list.head; temp; temp = temp->next, index++)
  810.         {
  811.             temp->index = index;
  812.  
  813.             if (!doing_switch && index < temp->hash_value)
  814.                 {
  815.                     int column;
  816.  
  817.                     printf ("      ");
  818.       
  819.                     for (column = 1; index < temp->hash_value; index++, column++)
  820.                         printf ("%s\"\",%s %s", l_brace, r_brace, column % 9 ? "" : "\n      ");
  821.       
  822.                     if (column % 10)
  823.                         printf ("\n");
  824.                     else 
  825.                         {
  826.                             printf ("%s\"%s\", %s%s\n", l_brace, temp->key, temp->rest, r_brace);
  827.                             continue;
  828.                         }
  829.                 }
  830.  
  831.             printf ("      %s\"%s\", %s%s\n", l_brace, temp->key, temp->rest, r_brace);
  832.  
  833.             /* Deal with links specially. */
  834.             if (temp->link)
  835.                 {
  836.                     LIST_NODE *links;
  837.  
  838.                     for (links = temp->link; links; links = links->link)
  839.                         {
  840.                             links->index = ++index;
  841.                             printf ("      %s\"%s\", %s%s\n", l_brace, links->key, links->rest, r_brace);
  842.                         }
  843.                 }
  844.  
  845.         }
  846.  
  847.   printf ("%s%s};\n\n", indent, indent);
  848. }
  849.  
  850. /* Generates C code for the hash function that returns the
  851.    proper encoding for each key word. */
  852.  
  853. static void print_hash_function( int max_hash_value )
  854. {
  855.   int max_column = 10;
  856.   int count       = max_hash_value;
  857.  
  858.   /* Calculate maximum number of digits required for MAX_HASH_VALUE. */
  859.  
  860.   while ((count /= 10) > 0)
  861.     field_width++;
  862.  
  863.   if (OPTION_ENABLED (option, GNU))
  864.     printf ("#ifdef __GNUC__\ninline\n#endif\n");
  865.   
  866.   printf (OPTION_ENABLED (option, ANSI) 
  867.           ? "static int\n%s (register const char *str, register int len)\n{\n  static %sunsigned %s hash_table[] =\n    {"
  868.           : "static int\n%s (str, len)\n     register char *str;\n     register unsigned int  len;\n{\n  static %sunsigned %s hash_table[] =\n    {",
  869.           GET_HASH_NAME (option), OPTION_ENABLED (option, CONST) ? "const " : "",
  870.           max_hash_value < 256 ? "char" : (max_hash_value < 65536 ? "short" : "int"));
  871.   
  872.   for (count = 0; count < ALPHABET_SIZE; ++count)
  873.     {
  874.       if (!(count % max_column))
  875.         printf ("\n    ");
  876.       
  877.       printf ("%*d,", field_width, occurrences[count] ? asso_values[count] : max_hash_value);
  878.     }
  879.   
  880.   /* Optimize special case of ``-k 1,$'' */
  881.   if (OPTION_ENABLED (option, DEFAULTCHARS)) 
  882.     printf ("\n    };\n  return %s + hash_table[str[len - 1]] + hash_table[str[0]];\n}\n\n",
  883.             OPTION_ENABLED (option, NOLENGTH) ? "0" : "len");
  884.   else
  885.     {
  886.       int key_pos;
  887.  
  888.       RESET (option);
  889.  
  890.       /* Get first (also highest) key position. */
  891.       key_pos = GET (option); 
  892.       
  893.       /* We can perform additional optimizations here. */
  894.       if (!OPTION_ENABLED (option, ALLCHARS) && key_pos <= key_list.min_key_len) 
  895.         { 
  896.           printf ("\n  };\n  return %s", OPTION_ENABLED (option, NOLENGTH) ? "0" : "len");
  897.           
  898.           for ( ; key_pos != EOS && key_pos != WORD_END; key_pos = GET (option))
  899.             printf (" + hash_table[str[%d]]", key_pos - 1);
  900.            
  901.           printf ("%s;\n}\n\n", key_pos == WORD_END ? " + hash_table[str[len - 1]]" : "");
  902.         }
  903.  
  904.       /* We've got to use the correct, but brute force, technique. */
  905.       else 
  906.         {                    
  907.           printf ("\n    };\n  register int hval = %s ;\n\n  switch (%s)\n    {\n      default:\n",
  908.                   OPTION_ENABLED (option, NOLENGTH) ? "0" : "len", OPTION_ENABLED (option, NOLENGTH) ? "len" : "hval");
  909.           
  910.           /* User wants *all* characters considered in hash. */
  911.           if (OPTION_ENABLED (option, ALLCHARS)) 
  912.             { 
  913.               int i;
  914.  
  915.               for (i = key_list.max_key_len; i > 0; i--)
  916.                 printf ("      case %d:\n        hval += hash_table[str[%d]];\n", i, i - 1);
  917.               
  918.               printf ("    }\n  return hval;\n}\n\n");
  919.             }
  920.           else /* do the hard part... */
  921.             {                
  922.               count = key_pos + 1;
  923.               
  924.               do
  925.                 {
  926.                   
  927.                   while (--count > key_pos)
  928.                     printf ("      case %d:\n", count);
  929.                   
  930.                   printf ("      case %d:\n        hval += hash_table[str[%d]];\n", key_pos, key_pos - 1);
  931.                 }
  932.               while ((key_pos = GET (option)) != EOS && key_pos != WORD_END);
  933.               
  934.               printf ("    }\n  return hval%s ;\n}\n\n", key_pos == WORD_END ? " + hash_table[str[len - 1]]" : "");
  935.           }
  936.       }
  937.   }
  938. }
  939.  
  940. /* Generates C code to perform the keyword lookup. */
  941.  
  942. static void print_lookup_function()
  943.   printf ("  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n    {\n\
  944.       register int key = %s (str, len);\n\n\
  945.       if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n        {\n\
  946.           register %schar *s = wordlist[key]", 
  947.           GET_HASH_NAME (option), OPTION_ENABLED (option, CONST) ? "const " : "");
  948.   if (key_list.array_type != default_array_type)
  949.     printf (".%s", GET_KEY_NAME (option));
  950.  
  951.   printf (";\n\n          if (%s*s == *str && !%s)\n            return %s",
  952.           OPTION_ENABLED (option, LENTABLE) ? "len == lengthtable[key]\n              && " : "",
  953.           OPTION_ENABLED (option, COMP) ? "strncmp (str + 1, s + 1, len - 1)" : "strcmp (str + 1, s + 1)",
  954.           OPTION_ENABLED (option, TYPE) && OPTION_ENABLED (option, POINTER) ? "&wordlist[key]" : "s");
  955.   printf (";\n        }\n    }\n  return 0;\n}\n");
  956. }
  957.  
  958. /* Generates the hash function and the key word recognizer function
  959.    based upon the user's Options. */
  960.  
  961. void print_output()
  962. {
  963.   int global_table = OPTION_ENABLED (option, GLOBAL);
  964.  
  965.   printf ("/* C code produced by gperf version %s */\n", version_string);
  966.   print_options();
  967.   
  968.   printf ("%s\n", key_list.include_src);
  969.   
  970.   /* Potentially output type declaration now, reference it later on.... */
  971.   if (OPTION_ENABLED (option, TYPE) && !OPTION_ENABLED (option, NOTYPE)) 
  972.     printf ("%s;\n", key_list.array_type);
  973.   
  974.   print_hash_function (print_min_max ());
  975.   
  976.   if (global_table)
  977.     if (OPTION_ENABLED (option, SWITCH))
  978.       {
  979.         if (OPTION_ENABLED (option, LENTABLE) && OPTION_ENABLED (option, DUP))
  980.           print_keylength_table ();
  981.         if (OPTION_ENABLED (option, POINTER) && OPTION_ENABLED (option, TYPE))
  982.           print_keyword_table ();
  983.       }
  984.     else
  985.       {
  986.         if (OPTION_ENABLED (option, LENTABLE))
  987.           print_keylength_table ();
  988.         print_keyword_table ();
  989.       }
  990.   /* Use the inline keyword to remove function overhead. */
  991.   if (OPTION_ENABLED (option, GNU)) 
  992.     printf ("#ifdef __GNUC__\ninline\n#endif\n");
  993.   
  994.   /* Use ANSI function prototypes. */
  995.   printf (OPTION_ENABLED (option, ANSI)
  996.           ? "%s%s\n%s (register const char *str, register int len)\n{\n"
  997.           : "%s%s\n%s (str, len)\n     register char *str;\n     register unsigned int len;\n{\n", 
  998.             OPTION_ENABLED (option, CONST) ? "const " : "", 
  999.             key_list.return_type, GET_FUNCTION_NAME (option));
  1000.   
  1001.   /* Use the switch in place of lookup table. */
  1002.   if (OPTION_ENABLED (option, SWITCH))
  1003.     {               
  1004.       if (!global_table)
  1005.         {
  1006.           if (OPTION_ENABLED (option, LENTABLE) && OPTION_ENABLED (option, DUP))
  1007.             print_keylength_table ();
  1008.           if (OPTION_ENABLED (option, POINTER) && OPTION_ENABLED (option, TYPE)) 
  1009.             print_keyword_table ();
  1010.         }
  1011.       print_switch ();
  1012.     }
  1013.   else                /* Use the lookup table, in place of switch. */
  1014.     {           
  1015.       if (!global_table)
  1016.         {
  1017.           if (OPTION_ENABLED (option, LENTABLE))
  1018.             print_keylength_table ();
  1019.           print_keyword_table ();
  1020.         }
  1021.       print_lookup_function ();
  1022.     }
  1023.  
  1024.         /*
  1025.         **    If there is additional code, read it from 
  1026.         **    the key file and write to output
  1027.         */
  1028.  
  1029.     if ( key_list.additional_code )
  1030.     {
  1031.         int        c;
  1032.  
  1033.         while ( ( c = getc( KeyFile ) ) != EOF )
  1034.             putchar( c );
  1035.     }
  1036. }
  1037.  
  1038.     /***********************************************************************\
  1039.     *                                                                        *
  1040.     * name:        sort                                                        *
  1041.     *                                                                        *
  1042.     * descr:    Sorts the keys by hash value                                *
  1043.     *                                                                        *
  1044.     \***********************************************************************/
  1045.  
  1046. void sort()
  1047.     key_list.hash_sort       = TRUE;
  1048.     key_list.occurrence_sort = FALSE;
  1049.  
  1050.     key_list.head = merge_sort( key_list.head );
  1051. }
  1052.  
  1053. /* Dumps the key list to stderr stream. */
  1054.  
  1055. static void dump() 
  1056. {      
  1057.   LIST_NODE *ptr;
  1058.  
  1059.   report_error ("\nList contents are:\n(hash value, key length, index, key set, uniq set, key):\n");
  1060.   
  1061.   for (ptr = key_list.head; ptr; ptr = ptr->next)
  1062.     report_error ("      %d,      %d,     %d, %s, %s, %s\n",
  1063.                   ptr->hash_value, ptr->length, ptr->index,
  1064.                   ptr->key_set, ptr->uniq_set, ptr->key);
  1065. }
  1066.  
  1067. /* Simple-minded constructor action here... */
  1068.  
  1069. void key_list_init()
  1070. {   
  1071.   key_list.total_keys      = 1;
  1072.   key_list.max_key_len     = NEG_MAX_INT;
  1073.   key_list.min_key_len     = MAX_INT;
  1074.   key_list.return_type     = default_return_type;
  1075.   key_list.array_type      = key_list.struct_tag  = default_array_type;
  1076.   key_list.head            = NULL;
  1077.   key_list.additional_code = FALSE;
  1078. }
  1079.  
  1080. /* Returns the length of entire key list. */
  1081.  
  1082. int length() 
  1083.   return key_list.list_len;
  1084. }
  1085.  
  1086. /* Returns length of longest key read. */
  1087.  
  1088. int max_key_length()
  1089.   return key_list.max_key_len;
  1090. }
  1091.  
  1092. /* DESTRUCTOR dumps diagnostics during debugging. */
  1093.  
  1094. void key_list_destroy() 
  1095.   if (OPTION_ENABLED (option, DEBUG))
  1096.     {
  1097.       report_error ("\nDumping key list information:\ntotal unique keywords = %d\
  1098. \ntotal keywords = %d\nmaximum key length = %d.\n", 
  1099.                     key_list.list_len, key_list.total_keys, key_list.max_key_len);
  1100.       dump ();
  1101.       report_error ("End dumping list.\n\n");
  1102.     }
  1103. }
  1104.